#include <iostream>
#include <unistd.h>
#include <stdlib.h>

using namespace std;

bool ParseLine(const std::string line,std::string &out1,std::string& out2,std::string sep)
{
  size_t pos = line.find(sep);
  if(pos != string::npos)
  {
    out1 = line.substr(0,pos);
    out2 = line.substr(pos + sep.size());
    return true;
  }
  return false;
}

int main()
{
  string method=getenv("METHOD");
  cerr<<method<<endl;
  string query_string;
  int  size;
  if(method=="GET")
  {
    query_string=getenv("QUERY_STRING");
    cerr<<query_string<<endl;
    //分离请求 目前只分析简单请求
    std::string str1,str2;
    ParseLine(query_string,str1,str2,"&");
    std::cerr << "cgi :" <<str1 << ":" << str2 <<  endl;
    //获得数据
    std::string key_a,value_a;
    std::string key_b,value_b;
    ParseLine(str1,key_a,value_a,"=");
    ParseLine(str2,key_b,value_b,"=");

    std::cerr << key_a << ":" << value_a << std::endl;
    std::cerr << key_b << ":" << value_b << std::endl;
    //发送到管道一份，本地打印一份
    std::cout << key_a << ":" << value_a << std::endl;
    std::cout << key_b << ":" << value_b << std::endl;
  }
  else if(method=="POST")
  {
    size=atoi(getenv("LENGTH"));
    cerr<<size<<endl;
    char c=0;
    while(size){
      read(0,&c,1);
      query_string.push_back(c);
      size--;
    }
    //分离请求
    std::string str1,str2;
    ParseLine(query_string,str1,str2,"&");
    std::cerr << "cgi :" <<str1 << ":" << str2 <<  endl;
    //获得数据
    std::string key_a,value_a;
    std::string key_b,value_b;
    ParseLine(str1,key_a,value_a,"=");
    ParseLine(str2,key_b,value_b,"=");

    std::cerr << key_a << ":" << value_a << std::endl;
    std::cerr << key_b << ":" << value_b << std::endl;
    //发送到管道一份，本地打印一份
    std::cout << key_a << ":" << value_a << std::endl;
    std::cout << key_b << ":" << value_b << std::endl;
    int x = atoi(value_a.c_str());
    int y = atoi(value_b.c_str());
    
    std::cout << key_a << "+" << key_b << "=" << x + y << std::endl;
    std::cout << key_a << "-" << key_b << "=" << x - y << std::endl;
    std::cout << key_a << "*" << key_b << "=" << x * y << std::endl;
    std::cout << key_a << "/" << key_b << "=" << x / y << std::endl; 
  }
  //cerr<<"调用了"<<endl;
  return 0;
}
